package com.handpay.framework.swiper;

import android.graphics.Bitmap;
import android.text.TextUtils;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.other.activity.ShowHtmlActivity;
import com.handpay.zztong.hp.config.UPConfig;
import com.handpay.zztong.hp.log.HPLog;

import java.util.Arrays;
import java.util.Hashtable;

/**
 * Created by jmshuai on 2014/8/12. 所有的个人刷卡器（没有键盘和屏幕）的刷卡器，都实现IPersonalSwiper。
 */
class BusinessSwiper implements IBusinessSwiper {
	private IPersonalSwiper mPersonalSwiper;
	private String mPlainPwd;
	private String mPlainAmount;
	private SwiperMode mSwiperMode;
	private Hashtable<String, String> mHTData = new Hashtable<String, String>();

	public BusinessSwiper(IPersonalSwiper personalSwiper) {
		mPersonalSwiper = personalSwiper;
	}

	@Override
	public Result affirmAmount(String amount, int timeout) {
		mPlainAmount = amount;
		return Result.OK;
	}

	@Override
	public Result inputPwd(String factor, int timeout) {
		if (TextUtils.isEmpty(mPlainPwd)) {
			return Result.CANCEL;
		}
		// 加密金额，和加密加密密码
		mHTData.clear();
		Hashtable<String, String> personalHash = mPersonalSwiper.getBankInfo();
		// 准备数据失败，当用户取消。因为很有可能是ic卡，输入密码的时候拔掉了卡
		if (null == personalHash) {
			HPLog.e(HPLog.YL_TAG, "personalHash:null");
			return Result.CANCEL;
		}
		mHTData.putAll(personalHash);
		// 新版 2.0.0 后加入IC 有效期 需要 13号密钥加密
		/*
		 * if(!TextUtils.isEmpty(mHTData.get(IBusinessSwiper.BANK_PLAIN_EXPIRE_DATE
		 * ))){ HPLog.i(HPLog.FDL_TAG,
		 * "BusinessSwiper  encData-- plainExpireDate:"
		 * +mHTData.get(IBusinessSwiper.BANK_PLAIN_EXPIRE_DATE)); String exDate
		 * = mPersonalSwiper.encData(mHTData.get(IBusinessSwiper.
		 * BANK_PLAIN_EXPIRE_DATE), ISwiperListener.KeyDataIndex, factor);
		 * HPLog.i(HPLog.FDL_TAG, "BusinessSwiper enc return exDate:"+exDate);
		 * if(!TextUtils.isEmpty(exDate)){
		 * mHTData.put(IBusinessSwiper.BANK_PLAIN_EXPIRE_DATE, exDate); }else{
		 * HPLog.i("FDL", "enc plainExpireDate error!"); } }
		 */

		if (!TextUtils.isEmpty(mPlainAmount)) {
			HPLog.i("BusinessSwiper", "enc amount:" + mPlainAmount);
			String encAmount;
			encAmount = mPersonalSwiper.encData(mPlainAmount, ISwiperListener.KeyDataIndex, factor);
			HPLog.i("BusinessSwiper", "enc amount result:" + encAmount);
			if (!TextUtils.isEmpty(encAmount)) {
				mHTData.put(BANK_AMOUNT_KEY, encAmount);
			} else {
				HPLog.i("BusinessSwiper", "enc amount error!");
				return Result.ERROR;
			}
		}
		if (null == mHTData.get(BANK_ACCOUNT_KEY)) {
			String plainAccount = mHTData.get(BANK_PLAIN_ACCOUNT_KEY);
//			((LandiSwiperM18)mPersonalSwiper).plainAccount = plainAccount;
			if (null != plainAccount) {
				HPLog.i("BusinessSwiper", "enc account:" + plainAccount);
				HPLog.i("BusinessSwiper", "SwiperMode:" + mSwiperMode);
				String encAccount;

				if (mSwiperMode == SwiperMode.NORMAL_TRANS) {
					HPLog.i("BusinessSwiper", "enc account CommonUtils.string2Hex(plainAccount):"+CommonUtils.string2Hex(plainAccount));
					encAccount = mPersonalSwiper.encData(CommonUtils.string2Hex(plainAccount), ISwiperListener.KeyDataIndex, factor);
				} else {
					HPLog.i("BusinessSwiper", "enc account plainAccount:"+plainAccount);
					encAccount = mPersonalSwiper.encData(plainAccount, ISwiperListener.KeyDataIndex, factor);
				}
				
				HPLog.i("BusinessSwiper", "enc account factor:"+factor+" result:" + encAccount);
				if (!TextUtils.isEmpty(encAccount)) {
					mHTData.put(BANK_ACCOUNT_KEY, encAccount);
				} else {
					HPLog.i("BusinessSwiper", "enc account error!");
					return Result.ERROR;
				}
			} else {
				HPLog.e("BusinessSwiper", "no enc account and no plain account! error");
				return Result.ERROR;
			}
		}
		HPLog.i("BusinessSwiper", "enc pin:" + mPlainPwd);
		String pin = mPersonalSwiper.encData(mPlainPwd, PIN_INDEX, factor);
		HPLog.i("BusinessSwiper", "enc pin result:" + pin);
		if (TextUtils.isEmpty(pin)) {
			HPLog.i("BusinessSwiper", "enc pin error!");
			return Result.ERROR;
		}
		mHTData.put(BANK_PAN_KEY, pin);
		// 在此之后加密充值有关的数据merchantId ,orderId,terminalId,
		if (ClientEngine.getInstance().getGlobal(BANK_TransactionType_KEY) != null && ClientEngine.getInstance().getGlobal(BANK_TransactionType_KEY).equals("PurchaseAdvice")) {
			HPLog.e("fyang", "新增内容");
			HPLog.e("fyang", "加密之前merchantId" + ShowHtmlActivity.map.get("merchantId"));
			HPLog.e("fyang", "加密之前的orderId" + ShowHtmlActivity.map.get("orderId"));
			HPLog.e("fyang", "加密之前的terminalId" + ShowHtmlActivity.map.get("terminalId"));
			HPLog.e("fyang", ShowHtmlActivity.map.get("transAmount") + "加密之前的amount" + CommonUtils.formatMoneyToPos(ShowHtmlActivity.map.get("transAmount"), UPConfig.SUPER_TRANS_AMOUNT_LEN));
			String merchantId = mPersonalSwiper.encData(ShowHtmlActivity.map.get("merchantId"), ISwiperListener.KeyDataIndex, factor);
			String orderId = mPersonalSwiper.encData(ShowHtmlActivity.map.get("orderId"), ISwiperListener.KeyDataIndex, factor);
			String terminalId = mPersonalSwiper.encData(ShowHtmlActivity.map.get("terminalId"), ISwiperListener.KeyDataIndex, factor);
			String transAmount = mPersonalSwiper.encData(CommonUtils.formatMoenyToUnionpay(ShowHtmlActivity.map.get("transAmount")), ISwiperListener.KeyDataIndex, factor);
			// 防止加密异常
			if (TextUtils.isEmpty(merchantId) || TextUtils.isEmpty(orderId) || TextUtils.isEmpty(terminalId) || TextUtils.isEmpty(transAmount)) {
				HPLog.e(HPLog.FDL_TAG, "merchantId:" + merchantId);
				HPLog.e(HPLog.FDL_TAG, "merchantId:" + orderId);
				HPLog.e(HPLog.FDL_TAG, "merchantId:" + terminalId);
				HPLog.e(HPLog.FDL_TAG, "merchantId:" + transAmount);
				HPLog.e(HPLog.FDL_TAG, "------加密异常--------");
				return Result.ERROR;
			}
			HPLog.e("merchantId", merchantId);
			HPLog.e("orderId", orderId);
			HPLog.e("terminalId", terminalId);
			HPLog.e("transAmount", transAmount);
			// 保存下,备用
			ClientEngine.getInstance().saveGlobal(BANK_MerchantID_KEY, merchantId);
			ClientEngine.getInstance().saveGlobal(BANK_OrderID_KEY, orderId);
			ClientEngine.getInstance().saveGlobal(BANK_TerminalID_KEY, terminalId);
			ClientEngine.getInstance().saveGlobal(BANK_TransAmount_KEY, transAmount);
			mHTData.put(BANK_MerchantID_KEY, merchantId);
			mHTData.put(BANK_OrderID_KEY, orderId);
			mHTData.put(BANK_TerminalID_KEY, terminalId);
			mHTData.put(BANK_TransAmount_KEY, transAmount);
		}
		return Result.OK;
	}

	/**
	 * 账账通六期暂不支持registerPwd
	 * 
	 * @param factor
	 *            加密的过程因子
	 * @param timeout
	 *            超时时限。以ms为单位
	 * @return
	 */
	@Override
	public SwipeResult registerPwd(String factor, int timeout) {
		return null;
	}

	@Override
	public Hashtable<String, String> getBankInfo() {
		Hashtable<String, String> result= (Hashtable<String, String>) mHTData.clone();
		mHTData.clear();
		return result;
	}

	@Override
	public void setPlainPwd(String pwd) {
		mPlainPwd = pwd;
	}

	@Override
	public String getCSN() {
		return mPersonalSwiper.getCSN();
	}

	@Override
	public boolean stopOperation() {
		return mPersonalSwiper.stopOperation();
	}

	@Override
	public boolean closeDevice() {
		mPlainAmount = null;
		mPlainPwd = null;
		if (null != mPersonalSwiper) {
			mPersonalSwiper.closeDevice();
			mPersonalSwiper = null;
		}
		return true;
	}

	@Override
	public SwipeResult swipeCard(String factor, int timeout) {
		return mPersonalSwiper.swipeCard(factor, timeout);
	}

	@Override
	public String encData(String data, String index, String factor) {
		return mPersonalSwiper.encData(data, index, factor);
	}

	@Override
	public Hashtable<String, String> batchEncData(Hashtable<Integer, String> htDatas, String factor) {
		return mPersonalSwiper.batchEncData(htDatas, factor);
	}

	@Override
	public boolean setMode(SwiperMode flag) {
		mSwiperMode = flag;
		return mPersonalSwiper.setMode(flag);
	}

	@Override
	public boolean isSwiperReady() {
		return mPersonalSwiper.isSwiperReady();
	}

	@Override
	public SwiperModel getSwiperModel() {
		if (null != mPersonalSwiper) {
			return mPersonalSwiper.getSwiperModel();
		}
		return null;
	}

	/**
	 * 磁道二不足40位，补F到40位！请确保传进来的数据不为空. 这个函数可以移到其它地方
	 * 
	 * @param track2
	 * @return
	 */
	public static String autoFillTrack2(String track2) {
		int length = track2.length();
		if (length < 40) {
			StringBuilder sb = new StringBuilder(40);
			sb.append(track2);
			char[] endF = new char[40 - length];
			Arrays.fill(endF, 'F');
			sb.append(endF);
			return sb.toString();
		}
		return track2;
	}

	@Override
	public boolean printBitMap(int position, Bitmap bitmap) {
		return false;
	}

	@Override
	public boolean printString(String data) {
		return false;
	}

	@Override
	public boolean print(String data, Bitmap bitmap) {
		return false;
	}

}
